import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { AtButton, AtForm, AtInput, AtSwitch } from 'taro-ui'

const http = require('../../utils/http.js')
const show = require('../../utils/show.js')

export default class TypeEdit extends Component {
    config = {
        navigationBarTitleText: '编辑分类'
    }

    constructor() {
        super(...arguments)
        this.state = {
            isAdd: true,
            formObj: { id: null, name: '' }
        }
    }

    componentWillMount() {
        let params = this.$router.params
        console.log(params)
        this.setState({ formObj: params, isAdd: !params.id })
    }
    componentDidMount() { }

    handleChangeName = (value) => this.handleChange("name", value)
    handleChange = (key, value) => {
        var formObj = this.state.formObj || {}
        formObj[key] = value
        this.setState({ formObj: formObj })
        return value
    }
    onSubmit = () => {
        if (!this.state.formObj.name) {
            show.warn("请输入名称")
            return
        }
        http.post2("/api/note/type/save", this.state.formObj)
            .then(res => {
                show.success('保存成功')
                    .then(() => {
                        Taro.navigateBack({ delta: 1 })
                    })
            })
    }

    render() {
        return (
            <View>
                <View style={{ marginTop: '10rpx', marginBottom: '10rpx' }}>
                    <H2>{isAdd ? '创建分类' : '修改分类'}</H2>
                </View>
                <AtForm onSubmit={this.onSubmit}>
                    <AtInput
                        name='name'
                        title='分类名'
                        type='text'
                        placeholder='请输入分类名'
                        value={this.state.formObj.name}
                        onChange={this.handleChangeName}
                    />
                    <AtButton formType='submit' type='primary'>保存</AtButton>
                </AtForm>
            </View>
        )
    }
}